import _Vue from 'vue'

const guid = require('guid')
const EventEmitter = require('events').EventEmitter
const { util: { getSize }, quantity: { mimeType } } = require('../util')

// 分片上传
function uploadFileBySlice (config) {
  let file = config.file

  let size = file.size
  let shardSize = 1024 * 1024// B

  let type = mimeType.find((item) => item.type === file.type)
  type = type ? type.name : file.type

  this.config = {
    file: file,
    fileType: config.fileType,
    XSMC: file.name,
    size,
    type,
    sizeZh: getSize(size),
    name: guid.raw(),
    status: 'wait',
    requestId: '',
    shardSize: shardSize,
    shardCount: Math.ceil(size / shardSize)
  }

  this.eventBus = new EventEmitter()
}

// 开始
uploadFileBySlice.prototype.start = async function () {
  let config = this.config
  if (config.status === 'cancel') return
  console.log('开始')
  config.status = 'uploading'

  try {
    let file = config.file

    // 请求前判断当前上传了多少
    let currentIndexInfo = await _Vue.prototype.$api.post.getCurrentIndex({
      name: config.name,
      fileType: config.fileType
    })

    let startIndex = 0
    // item.progress = Math.round(startIndex / item.shardCount * 10000) / 100;

    if (!currentIndexInfo.errno) startIndex = currentIndexInfo.data

    for (let i = startIndex; i < config.shardCount && config.status === 'uploading'; i++) {
      config.requestId = guid.raw()
      let start = i * config.shardSize
      let end = Math.min(config.file.size, start + config.shardSize)

      let form = new FormData()
      form.append('data', file.slice(start, end))
      form.append('XSMC', config.XSMC)
      form.append('name', config.name)
      form.append('fileType', config.fileType)
      form.append('total', config.shardCount)
      form.append('index', i + 1)

      let res = await _Vue.prototype.$api.post.uploadFileBySlice(form, {}, config.requestId)
      // console.log(`发送第${i + 1}片，共${item.shardCount}片`, res);
      if (res.errno) {
        console.log('有错', res.errmsg)
        config.status = 'fail'
        break
      }
      if (res.data.path) {
        config.status = 'success'
        config.path = res.data.path
      }

      let progress = Math.round((i + 1) / config.shardCount * 10000) / 100
      this.eventBus.emit('progress', progress)
    }
    this.eventBus.emit('success', {
      XSMC: config.XSMC,
      name: config.name,
      path: config.path
    })
    console.log(config.XSMC + '上传成功:', config.path)
  } catch (e) {
    if (e.message === 'pause') {
      console.error(`因暂停取消请求【${config.XSMC}】`)
    } else if (e.message === 'cancel') {
      console.error(`取消请求【${config.XSMC}】`)
    } else {
      config.status = 'fail'
      this.eventBus.emit('fail', e)
      console.log('上传失败')
      console.log(e)
    }
  } finally {
    console.log('结束了')
  }
}
// 取消
uploadFileBySlice.prototype.cancel = async function (msg) {
  let config = this.config
  if (config.status === 'cancel') return
  console.log('取消')
  config.status = 'cancel'
  this.eventBus.emit('cancel')
  await _Vue.prototype.$api.cancel(config.requestId, 'cancel')
}
// 暂停
uploadFileBySlice.prototype.pause = async function () {
  console.log('暂停')
  let config = this.config
  config.status = 'pause'
  this.eventBus.emit('pause')
  await _Vue.prototype.$api.cancel(config.requestId, `pause`)
}

export default (Vue, option) => {
  Vue.prototype.$methods = {
    uploadFileBySlice// 分片上传文件
  }
}
